package logic

import (
	"context"
	"errors"
	"new-goods/models/mysql"

	"new-goods/goodsrpc/goodsrpc"
	"new-goods/goodsrpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type GoodsAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGoodsAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GoodsAddLogic {
	return &GoodsAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 添加
func (l *GoodsAddLogic) GoodsAdd(in *goodsrpc.GoodsAddRequest) (*goodsrpc.GoodsAddResponse, error) {
	// todo: add your logic here and delete this line

	var findGoods mysql.Goods

	begin := mysql.DB.Begin()

	err := findGoods.FindGoodsByName(begin, in.ClassName)
	if err != nil {
		begin.Rollback()
		return nil, errors.New("当前商已存在")
	}

	class := &mysql.Class{
		Name: in.Name,
	}

	err = class.FindClassByName(begin, in.ClassName)
	if err != nil {
		begin.Rollback()
		return nil, err
	}

	goods := &mysql.Goods{
		Name:    in.Name,
		Price:   float64(in.Price),
		Stock:   in.Stock,
		Image:   in.Image,
		ClassId: int64(class.ID),
	}

	err = goods.GoodsAdd(begin)
	if err != nil {
		begin.Rollback()
		return nil, err
	}

	begin.Commit()

	return &goodsrpc.GoodsAddResponse{
		GoodsId: int64(goods.ID),
	}, nil
}
